<template>
  <div class="main-app">
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="form-inline">
        <el-form-item label="产生时间:">
          <div class="block">
            <el-date-picker v-model="formInline.transportTime" type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" style="width: 100%;" format="yyyy 年 MM 月 dd 日"
            />
          </div>
        </el-form-item>
        <el-form-item label="废物名称:">
          <el-input v-model="formInline.name" clearable />
        </el-form-item>
        <el-form-item label="废物代码:">
          <el-input v-model="formInline.codeContent" clearable />
        </el-form-item>
        <!--      <el-form-item label="废物类别:">
          <el-input v-model="formInline.waste" clearable />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh-right" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="show-result">

      <!-- 加载动态菜单 -->
      <el-form :inline="true" class="form-inline">
        <el-form-item v-for="item in toolbtn" :key="item.id">
          <el-button type="primary" :icon="item.meta.icon" @click="showViews(item.name)">
            {{ item.meta.title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <div> 当前页统计： 容器总数量：{{ summaryWastCount }} 个 | 废物总重量：
            {{ summaryWastWeight }} 吨
          </div>
        </el-form-item>
      </el-form>

      <!-- <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-sold-out" @click="view">
            接收废物入库
          </el-button>
        </el-form-item>
        <el-form-item>
          <div> 当前页统计： 容器总数量：{{ summaryWastCount }} 个 | 废物总重量：
            {{ summaryWastWeight }} 吨
          </div>
        </el-form-item>
      </el-form> -->

      <div class="result" style="margin-top: -40px;">
        <div class="tool">
          <el-button type="primary" size="mini" icon="el-icon-notebook-1" :disabled="deleteDisabled" plain @click="exportData" />
          <el-button type="primary" size="mini" icon="el-icon-printer" plain @click="printData" />
        </div>
        <el-table id="table" ref="multipleTable" v-loading="loading" border :data="tableData" tooltip-effect="dark"
                  style="width: 100%" @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <!-- <el-table-column prop="areaNumber" label="行政区域代码" width="110" /> -->
          <el-table-column prop="name" label="废物名称" width="100" />
          <el-table-column prop="number" label="数字识别码" width="100" />
          <el-table-column prop="categoryContent" label="废物类别" width="80" />
          <el-table-column prop="codeId" label="废物代码" width="100" />

          <!-- <el-table-column prop="hazardousSubstancesName" label="危险废物" width="100" /> -->
          <el-table-column prop="characteristicContent" label="危险特性" width="80" />
          <!-- <el-table-column prop="physicalProperties" label="废物形态" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.physicalProperties | parsePhysicalProperties }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="physicalProperties" label="废物形态" width="100">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.physicalPropertiesColor ">
                {{ scope.row.physicalPropertiesName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hwUtilizeDisposalMethod" label="利用处置方式" width="110" />
          <el-table-column prop="pos" label="贮存设施" width="150" />
          <!-- <el-table-column prop="disposalFacilitiesType" label="设施类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.disposalFacilitiesType | parseWarehouseCategory }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="disposalFacilitiesType" label="设施类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.disposalFacilitiesTypeColor ">
                {{ scope.row.disposalFacilitiesTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="wareHouseLocationName" label="贮存库位" width="100" /> -->
          <!-- <el-table-column prop="containerCategory" label="包装类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.containerCategory | parseContainerType }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="containerCategory" label="包装类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.containerCategoryColor ">
                {{ scope.row.containerCategoryName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="packagingNumber" label="包装数量" width="100" />
          <el-table-column prop="wastWeight" label="入库前重量 (吨)" width="100" />
          <el-table-column prop="produceInBatchNumber" label="入库批次号" width="100" />
          <el-table-column prop="inOutAmount" label="入库量 (吨)" width="100" />
          <el-table-column prop="createTime" label="产生入库时间" width="110">
            <template slot-scope="scope">
              {{ scope.row.createTime | parseDate }}
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="操作人" width="100" />
          <el-table-column prop="wpcName" label="产废单位" width="200" />

          <el-table-column prop="describe" label="备注" width="100" />
        </el-table>
        <div class="page">
          <el-pagination background :current-page.sync="currentPage" layout="total,prev, pager, next,sizes" :total="total"
                         :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" @current-change="handleCurrentChange" @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>

    <div class="dialog_diy">
      <el-dialog :visible.sync="dialogVisible" width="70%" style="margin-top: -50px;" @close="closeDialog">
        <div slot="title" style="background:#1890FF;color: white;">
          <div style="padding:15px 20px;">新增接收废物入库</div>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row>
            <el-divider content-position="left">转移申请信息</el-divider>
            <el-col :span="12">
              <el-form-item label="转运申请编号:" required prop="applyId">
                <el-input v-model="form.applyObj.number" disabled style="width: 90%;" />
              </el-form-item>

              <el-form-item label="产废单位名称:">
                <el-input v-model="form.applyObj.wpcName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="运输单位名称:">
                <el-input v-model="form.applyObj.tcName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="司机:">
                <el-input v-model="form.applyObj.vehicleDriverName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="押运员:">
                <el-input v-model="form.applyObj.vehicleEscortName" disabled style="width: 90%;" />
              </el-form-item>

              <el-form-item label="车牌号:">
                <el-input v-model="form.applyObj.vehiclePlateNumber" disabled style="width: 90%;" />
              </el-form-item>

              <el-form-item label="接收单位名称:">
                <el-input v-model="form.applyObj.ccName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="接收单位联系人:">
                <el-input v-model="form.applyObj.collectionContactsName" disabled style="width: 90%;" />
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item label="转运计划编号:">
                <el-input v-model="form.applyObj.transferPlanNumber" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="通讯地址:">
                <el-input v-model="form.applyObj.wpcAddress" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="通讯地址:">
                <el-input v-model="form.applyObj.tcAddress" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="司机手机:">
                <el-input v-model="form.applyObj.vehicleDriverPhone" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="押运员手机:">
                <el-input v-model="form.applyObj.vehicleEscortPhone" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="车型:">
                <el-input v-model="form.applyObj.vehicleModel" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="通讯地址:">
                <el-input v-model="form.applyObj.ccAddress" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="联系人手机:">
                <el-input v-model="form.applyObj.collectionContactsPhone" disabled style="width: 90%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">废物信息</el-divider>
          <el-row style="margin-top: 10px">
            <el-col :span="12">
              <el-form-item label="废物名称:" required prop="wastName">
                <el-input v-model="form.wastName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物类别:">
                <el-input v-model="form.wastObj.categoryContent" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物代码:">
                <el-input v-model="form.wastObj.codeId" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="危险特性:">
                <el-input v-model="form.wastObj.characteristicContent" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="原始重量(吨):">
                <el-input v-model="form.wastObj.inAmount" disabled style="width: 90%;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="容器类型:">
                <el-input v-model="form.wastObj.containerCategory" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="危害成分:">
                <el-input v-model="form.wastObj.hazardousSubstancesName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物形态:">
                <el-input v-model="form.wastObj.physicalProperties" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="来源及生产工序:">
                <el-input v-model="form.wastObj.processContent" disabled style="width: 90%;" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">入库信息</el-divider>
          <el-row style="margin-top: 10px">
            <el-col :span="12">
              <el-form-item label="存放仓库:" required prop="wareHouseId">
                <el-select v-model="form.wareHouseId" placeholder="请选择" style="width: 90%;" @change="changeWastHouse">

                  <el-option v-for="item in houseList" :key="item.id" :label="item.name" :value="item.id" />
                  <!-- <el-option label="未填写" value="" /> -->
                </el-select>
              </el-form-item>
              <el-form-item label="入库量 (吨):" required prop="inAmount">
                <el-input v-model="form.inAmount" type="number" style="width: 90%;" @blur="changeInAmount" />
              </el-form-item>
              <el-form-item label="容器类别:" prop="containerType">
                <el-radio-group v-model="form.containerType">
                  <el-radio v-for="(item, index) in containerOptions" :key="index" :label="item.value">{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="禁忌与应急措施:" prop="safetyPrecautions">
                <el-select v-model="form.safetyPrecautionsId" filterable placeholder="请选择" clearable style="width: 95%"
                           @change="safetyPrecautionsChange"
                >
                  <el-option v-for="item in safetyPrecautionsOptions" :key="item.id" :label="item.content" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存放库位:" required prop="wareHouseLocationId">
                <el-select v-model="form.wareHouseLocationId" placeholder="请选择" style="width: 90%;" @change="changeWastHouseLocation">
                  <el-option v-for="item in housePosList" :key="item.id" :label="item.name" :value="item.id" />
                  <!-- <el-option label="未填写" value="" /> -->
                </el-select>
              </el-form-item>
              <el-form-item label="入库批次号:" required prop="batchLabel">
                <el-input v-model="form.batchLabel" style="width: 90%;" />
              </el-form-item>
              <el-form-item label="危险标语:" prop="termId">
                <el-select v-model="form.termId" filterable placeholder="请选择" clearable style="width: 90%" @change="termContentChange">
                  <el-option v-for="item in termContentOptions" :key="item.id" :label="item.content" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注原因:">
                <el-select v-model="form.remarksId" placeholder="请选择" clearable style="width: 90%;" @change="changeRemark">
                  <el-option v-for="item in resultRemarkList" :key="item.code" :label="item.value" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="备注:">
              <el-input v-model="form.remarks" type="textarea" style="width:95%;" />
            </el-form-item>
          </el-row>

          <el-row style="margin-top: 40px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button type="primary" @click="selectedForm">选择转移申请</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="selectedWasteType">选择待入库废物</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="success" :loading="isInstoreing" @click="inStore('10')">入库并打印标签</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" :loading="isInstoreing" @click="inStore('0')">确认入库</el-button>
              </el-form-item>
              <!-- <el-form-item>
                <el-button type="warning" @click="inStore('60')">入库完成</el-button>
              </el-form-item> -->
              <el-form-item>
                <el-button @click="cancel">取 消</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// Table组件相关逻辑，需要引用
import {
  pageMixin
} from "../../../mixins/index";
import {
  transportFromState,
  ContainerType,
  PhysicalProperties,
  WarehouseCategory
} from "../../../utils/resource.js";

import {
  getInOutStoreRecordList,
  getWareHouseList,
  getPosListByWareHouseId,
  addInStoreOfCollectedWast
} from '../../../api/warehouse.js';
import {
  parseTime,
  getFloat,
  getInOutCode,
} from '../../../utils/index.js';
import {
  // getWasteTypeList,
  // getWasteCodeList,
  // getSourceProcessList,
  // addWasteInformation,
  // getWasteInformationById,
  getWasteTermList,
  GetAllHWSafetyprecautionsList,
  // GetWasteInformationListForProductAsync,
  getDictionaryListByType
} from '../../../api/system.js';
export default {
  filters: {
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
    },
    parseContainerType(value) {
      if (value) {
        var obj = ContainerType.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },
    parsePhysicalProperties(value) {
      if (value) {
        var obj = PhysicalProperties.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },
    parseWarehouseCategory(value) {
      if (value) {
        var obj = WarehouseCategory.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },

  },

  mixins: [pageMixin],
  data() {
    return {
      isInstoreing: false,
      transportFromStateOption: transportFromState,
      formInline: {
        transportTime: ["", ""],
        name: "",
        codeContent: "",
      },

      form: {
        id: "",
        applyObj: {},
        applyId: '',

        formId: "",
        wastObj: {},
        formObj: {},
        wastName: "",
        inAmount: 0,
        allremarks: "",
        remarks: "",
        describe: "",
        batchLabel: "",
        disposalFacilitiesType: ""
      },

      dialogVisible: false,
      resultRemarkList: [],
      houseList: [],
      housePosList: [],

      containerOptions: ContainerType,
      termContentOptions: [],
      safetyPrecautionsOptions: [],

      rules: {
        inAmount: [{
          required: true,
          message: "请填写入库量",
          trigger: "blur"
        }],

        batchLabel: [{
          required: true,
          message: "请填写入库批次号",
          trigger: "blur"
        }],
        applyId: [{
          required: true,
          message: "请填选择转移申请",
          trigger: "blur"
        }],

        wastName: [{
          required: true,
          message: "请选择需要入库的危险废物",
          trigger: "blur"
        }],

        wareHouseId: [{
          required: true,
          message: "请选择贮存仓库",
          trigger: "change"
        }],
        wareHouseLocationId: [{
          required: true,
          message: "请选择贮存库位",
          trigger: "change"
        }],
      },
      toolbtn: [] // 列表顶部按钮
    };
  },
  async created() {
    var tempInhouseObjInfo_Receive_ACC = JSON.parse(localStorage.getItem('tempInhouseObjInfo_Receive_ACC'));
    if (tempInhouseObjInfo_Receive_ACC) {
      this.form = tempInhouseObjInfo_Receive_ACC;
      if (this.form.wastObj) {
        var obj = WarehouseCategory.find((p) => p.value === `${this.form.wastObj.containerCategory}`);
        if (obj) {
          this.form.wastObj.containerCategory = obj.label
        }

        var obj2 = PhysicalProperties.find((p) => p.value === `${this.form.wastObj.physicalProperties}`);
        if (obj) {
          this.form.wastObj.physicalProperties = obj2.label
        }
      }
      this.dialogVisible = true;
    }
    await this.init();
  },
  methods: {
    // 列表顶部功能按钮点击事件
    showViews(action) {
      // console.log(action);
      switch (action) {
        case '接收废物入库':
          this.view();
          break;
      }
    },
    termContentChange(e) {
      var _this = this;
      var obj = _this.termContentOptions.find(item => {
        return item.id === e
      })
      if (obj) {
        _this.form.termContent = obj.content;
        _this.form.termId = obj.id;
      }
    },
    safetyPrecautionsChange(e) {
      var _this = this;

      var obj = _this.safetyPrecautionsOptions.find(item => {
        return item.id === e
      })
      if (obj) {
        _this.form.safetyPrecautions = obj.content;
        _this.form.safetyPrecautionsId = obj.id;
      }
    },
    async init() {
      this.tableData = [];
      this.loading = true;
      const {
        data,
        count
      } = await getInOutStoreRecordList({
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          "OperateType": "10",
          "InOutType": "30",
          "Name": this.formInline.name,
          "CodeContent": this.formInline.codeContent,
          "StartTime": parseTime(this.formInline.transportTime[0]) === null ? "" : parseTime(this.formInline
            .transportTime[0]).substring(0, 10),
          "EndTime": parseTime(this.formInline.transportTime[1]) === null ? "" : parseTime(this.formInline
            .transportTime[1]).substring(0, 10)

        })
      });
      data.forEach(item => {
        item.pos = (item.wareHouseName === null ? "" : item.wareHouseName + "-") + (item
          .wareHouseLocationName === null ? "" : item.wareHouseLocationName)
      })
      this.tableData = data;
      this.undataSummaryData(data);
      this.tableData.forEach(item => {
        item.pos = (item.wareHouseName === null ? "" : item.wareHouseName + "-") + (item
          .wareHouseLocationName === null ? "" : item.wareHouseLocationName)

        var obj = PhysicalProperties.find((p) => p.value === `${item.physicalProperties}`);
        if (obj) {
          item.physicalPropertiesName = obj.label;
          item.physicalPropertiesColor = obj.color;
        } else {
          item.physicalPropertiesName = "无数据";
          item.physicalPropertiesColor = "red";
        }

        var obj2 = WarehouseCategory.find((p) => p.value === `${item.disposalFacilitiesType}`);
        if (obj2) {
          item.disposalFacilitiesTypeName = obj2.label;
          item.disposalFacilitiesTypeColor = obj2.color;
        } else {
          item.disposalFacilitiesTypeName = "无数据";
          item.disposalFacilitiesTypeColor = "red";
        }

        var obj3 = ContainerType.find((p) => p.value === `${item.containerCategory}`);
        if (obj3) {
          item.containerCategoryName = obj3.label;
          item.containerCategoryColor = obj3.color;
        } else {
          item.containerCategoryName = "无数据";
          item.containerCategoryColor = "red";
        }
      });
      this.total = count;
      this.loading = false;

      // 初始化按钮数据
      this.toolbtn = JSON.parse(localStorage.getItem('接收废物入库台账'));
      // console.log(this.toolbtn);

      await this.getWareHouseList();
    },
    undataSummaryData(tableDataList) {
      this.summaryWastCount = 0;
      this.summaryWastWeight = 0;

      tableDataList.forEach(item => {
        if (item.inAmount < 0) {
          item.inAmount = 0
        }
        this.summaryWastWeight += item.inOutAmount;
        this.summaryWastCount += 1;
      })
      this.summaryWastWeight = getFloat(this.summaryWastWeight, 5)
    },
    async changeRemark(val) {
      this.form.remarksId = val;
    },
    selectedForm() {
      localStorage.setItem('tempInhouseObjInfo_Receive_ACC', JSON.stringify(this.form));
      this.$router.push("/warehouse/inhouse_receive/formList");
    },
    changeInAmount(val) {
      if (this.form.inAmount <= 0) {
        this.form.inAmount = 0;
      }
    },

    async changeWastHouse(val) {
      this.form.wareHouseId = val;
      var obj = this.houseList.find((p) => p.id === `${val}`);
      if (obj) {
        this.form.wareHouseName = obj.name;
        this.form.disposalFacilitiesType = obj.type;
      } else {
        this.form.wareHouseName = "";
        this.form.disposalFacilitiesType = "";
      }
      await this.getPosListByWareHouseId(val);
    },

    async changeWastHouseLocation(val) {
      this.form.wareHouseLocationId = val;
      var obj = this.housePosList.find((p) => p.id === `${val}`);
      if (obj) {
        this.form.wareHouseLocationName = obj.name;
      } else {
        this.form.wareHouseLocationName = ""
      }
    },

    async getWareHouseList() {
      var searchDatas = {
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          // "OperateType": "10",
          // "InOutType": "10",
          // "Name": this.formInline.name,
          // "CodeContent": this.formInline.codeContent,
          // "StartTime": parseTime(this.formInline.transportTime[0]) === null ? "" : parseTime(this.formInline
          //   .transportTime[0]).substring(0, 10),
          // "EndTime": parseTime(this.formInline.transportTime[1]) === null ? "" : parseTime(this.formInline
          //   .transportTime[1]).substring(0, 10)
        })
      };
        // 并行获取数据
      Promise.all([await getWareHouseList(),
        await getDictionaryListByType("101"),
        await getWasteTermList(),
        await GetAllHWSafetyprecautionsList(searchDatas)
      ])
        .then((result) => {
          this.resultRemarkList = result[1].data;
          this.houseList = result[0].data;

          this.termContentOptions = result[2].data;
          this.safetyPrecautionsOptions = result[3].data;

          if (this.houseList) {
            if (!this.form.wareHouseId) {
              this.form.wareHouseId = this.houseList[0].id;
            }
            var obj = this.houseList.find((p) => p.id === `${this.form.wareHouseId}`);
            if (obj) {
              this.form.wareHouseName = obj.name;
              this.form.disposalFacilitiesType = obj.type;
            }
          }
        })
        .then(async() => {
          if (this.form.wareHouseId) {
            await this.getPosListByWareHouseId(this.form.wareHouseId);
          }
        })
    },
    async getPosListByWareHouseId(wareHouseId) {
      const {
        data
      } = await getPosListByWareHouseId(wareHouseId)
      this.housePosList = [];
      this.housePosList = data;
      if (this.housePosList) {
        if (this.housePosList.length !== 0) {
          this.form.wareHouseLocationId = this.housePosList[0].id;
          this.form.wareHouseLocationName = this.housePosList.find((p) => p.id === `${this.housePosList[0].id}`)
            .name;
        } else {
          this.form.wareHouseLocationId = "";
          this.form.wareHouseLocationName = "";
        }
      } else {
        this.form.wareHouseLocationId = "";
        this.form.wareHouseLocationName = "";
      }
    },

    // 关闭dialog时候触发
    closeDialog() {
      // 清除转运申请详情存在localstroage的临时表单内容
      this.resectInfo();
    },
    cancel() {
      this.$router.push("/warehouse/inhouse_receive");
      this.dialogVisible = false;
      // 清除转运申请详情存在localstroage的临时表单内容
      this.resectInfo();
    },
    resectInfo() {
      localStorage.removeItem('tempInhouseObjInfo_Receive_ACC');
      this.form = {
        id: "",
        applyObj: {},
        applyId: '',

        formId: "",
        wastObj: {},
        formObj: {},
        wastName: "",
        inAmount: 0,
        allremarks: "",
        remarks: "",
        describe: "",
        batchLabel: "RK" + getInOutCode(),
        disposalFacilitiesType: ""
      }
    },

    downPDF() {
      this.$message.error('功能等待完成');
    },
    view() {
      if (this.$refs['form']) {
        // 重置表单验证
        this.$refs.form.resetFields()
      }
      this.resectInfo();
      this.dialogVisible = true;
    },
    selectedWasteType() {
      if (!this.form.applyId) {
        this.$message.error('请选择转移申请');
        return;
      }
      localStorage.setItem('tempInhouseObjInfo_Receive_ACC', JSON.stringify(this.form));
      this.$router.push("/warehouse/inhouse_receive/index_WastObjList");
    },
    // 除数，被除数， 保留的小数点后的位数
    Chufunction(arg1, arg2, digit) {
      var t1 = 0;
      var t2 = 0;
      var r1;
      var r2;
      console.log(arg1);
      console.log(arg2);
      try {
        t1 = arg1.toString().split(".")[1].length
      } catch (e) {
        console.log("错误:" + e.message);
      }
      try {
        t2 = arg2.toString().split(".")[1].length
      } catch (e) {
        console.log("错误:" + e.message);
      }
      r1 = Number(arg1.toString().replace(".", ""))
      r2 = Number(arg2.toString().replace(".", ""))
      // 获取小数点后的计算值
      var result = ((r1 / r2) * Math.pow(10, t2 - t1)).toString();

      var result2 = result.split(".")[1];
      if (result2 === "" || result2 === null || result2 === undefined) {
        return Number(result.split(".")[0]);
      } else {
        result2 = result2.substring(0, digit > result2.length ? result2.length : digit);
        return Number(result.split(".")[0] + "." + result2);
      }
      // if (result2) {
      //   result2 = result2.substring(0, digit > result2.length ? result2.length : digit);
      //   return Number(result.split(".")[0] + "." + result2);
      // }
      // return Number(result);
    },
    async inStore(type) {
      // 校验必填项
      this.$refs["form"].validate(async(valid) => {
        if (valid) { // 校验成功
          if (getFloat(this.form.inAmount, 5) <= 0) {
            this.$message.error('入库重量需大于0');
            return;
          }

          var text = `本次入库${this.form.inAmount}吨, 是否继续?`;
          if (getFloat(this.form.inAmount, 5) !== getFloat(this.form.wastObj.inAmount, 5)) {
            var mm = this.Chufunction(Math.abs(this.form.inAmount - this.form.wastObj.inAmount), this.form
              .wastObj.inAmount, 4) * 100;
            if (mm.toString().length > 5) {
              mm = mm.toString().substr(0, 5); // 截取从第1个开始往后数5位之间的字符
            }

            // text = `本次出库${this.form.outAmount}吨，原始库存${this.form.wastObj.inAmount}吨, 损耗率为${mm}%，是否确认?`;
            var textType = "损耗率";
            if (this.form.inAmount > this.form.wastObj.inAmount) {
              textType = "误差率";
            }
            text =
                `本次入库<span style="color:red; font-size: 18px; font-weight: 700;">${this.form.inAmount}吨</span>，原始库存<span style="color:red; font-size: 18px; font-weight: 700;">${this.form.wastObj.inAmount}吨</span>, ${textType}为<span style="color:red; font-size: 18px; font-weight: 700;">${mm}%</span>，是否确认?`;
          }
          this.$confirm(text, "提示", {
            dangerouslyUseHTMLString: true, // 开启Html时用
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async() => {
            var obj = this.resultRemarkList.find((p) => p.code === `${this.form.remarksId}`);

            if (obj) {
              this.form.allremarks = obj.value;
              this.form.allremarks += this.form.remarks ? ("," + this.form.remarks) : "";
            } else {
              this.form.allremarks = this.form.remarks;
            }
            let data = {};
            let message = "";
            let transferApplyStatus = this.form.applyObj.type.toString(); // (联单状态)
            switch (type) {
              case "60":
                transferApplyStatus = "60"
                break;
            }

            data = {
              HazardousWasteIds: this.form.wastObj.id,
              WareHouseId: this.form.wareHouseId,
              WareHouseName: this.form.wareHouseName,
              WareHouseLocationId: this.form.wareHouseLocationId,
              WareHouseLocationName: this.form.wareHouseLocationName,
              InAmount: getFloat(this.form.inAmount, 5),
              Remarks: this.form.allremarks,
              DisposalMethod: "贮存",
              "TransferApplyId": this.form.applyId, // "转运申请ID"
              "TransferApplyStatus": transferApplyStatus, // (转运申请状态)
              DisposalFacilitiesType: this.form.disposalFacilitiesType,
              "BatchLabel": this.form.batchLabel,
              "InOutType": "30", // (出入库类型  10: 次生入库 20: 产生台账  30: 接收入库 40: 转移出库 50: 委外转移出库)

              // 新增参数
              containerCategory: this.form.containerType,
              TermId: this.form.termId,
              TermContent: this.form.termContent,
              SafetyPrecautionsId: this.form.safetyPrecautionsId,
              SafetyPrecautions: this.form.safetyPrecautions,
            };
            this.isInstoreing = true;

            message = "废物入库成功";
            const {
              success,
              msg
            } = await addInStoreOfCollectedWast(data);

            if (success) {
              // 清除转运申请详情存在localstroage的临时表单内容
              localStorage.removeItem('tempInhouseObjInfo_Receive_ACC');
              this.dialogVisible = false;
              await this.init();
              this.$notify({
                title: "成功",
                message: message,
                type: "success",
                duration: 3000,
              });
              this.isInstoreing = false;
            } else {
              this.$notify.error({
                title: "失败",
                message: msg,
                duration: 3000,
              });
              this.isInstoreing = false;
            }

            if (type === '10') { // 保存并打印
              // todu
              this.$notify.error({
                title: "提示",
                message: "功能暂未开放",
                duration: 3000,
              });
            }
          });
        }
      });
    },

    async reset() {
      this.formInline = {
        transportTime: ["", ""],
        number: "",
        status: "",
        characteristic: "",
      };
      await this.init();
    },
  },
};
</script>

<style lang="scss" scoped>
  .result {
    margin-top: 10px;
  }

  .page {
    margin-top: 20px;
    text-align: right;
    margin-bottom: 40px;
  }

  .show-result {
    margin-top: 10px;
  }

  .dialog_diy {
    ::v-deep .el-dialog__wrapper {

      // eslint-disable-line
      .el-dialog {

        .el-dialog__body {
          padding: 0px;
        }

        .el-dialog__header {
          padding: 0px;
        }

        .el-dialog__headerbtn {
          top: 5px;
          right: 5px;
          padding-top: 10px;
        }

        .el-dialog__headerbtn .el-dialog__close {
          color: #fff;
          height: 30px;
          width: 35px;
        }

        .el-dialog__headerbtn .el-dialog__close:hover {
          color: gray;
        }
      }
    }
  }
</style>
